/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.cloud.business.usercenter.controller;

import com.lvyh.lightframe.cloud.business.usercenter.service.SysUserService;
import com.lvyh.lightframe.cloud.common.annotation.CurrentUser;
import com.lvyh.lightframe.cloud.common.model.LoginAppUser;
import com.lvyh.lightframe.cloud.common.model.PageResult;
import com.lvyh.lightframe.cloud.common.model.Result;
import com.lvyh.lightframe.cloud.common.model.SysRole;
import com.lvyh.lightframe.cloud.common.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * 用户模块api
 */
@Slf4j
@RestController
public class SysUserController {
    private static final String ADMIN_CHANGE_MSG = "超级管理员不给予修改";

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据access_token当前登录用户 LoginAppUser
     */
    @GetMapping("/users/current")
    public Result<LoginAppUser> getLoginAppUser(@CurrentUser SysUser user) throws Exception {
        return Result.succeed(sysUserService.getLoginAppUser(user));
    }

    /**
     * 查询用户实体对象SysUser
     */
    @GetMapping(value = "/users/name/{username}")
    public SysUser selectByUsername(@PathVariable String username) throws Exception {
        return sysUserService.selectByUsername(username);
    }

    /**
     * 根据用户名查询用户登录对象LoginAppUser
     */
    @GetMapping(value = "/users-anon/login", params = "username")
    public LoginAppUser findByUsername(String username) throws Exception {
        return sysUserService.findByUsername(username);
    }

    /**
     * 通过手机号查询用户、角色信息
     */
    @GetMapping(value = "/users-anon/mobile", params = "mobile")
    public SysUser findByMobile(String mobile) throws Exception {
        return sysUserService.findByMobile(mobile);
    }

    @GetMapping(value = "/users-anon/openId", params = "openId")
    public SysUser findByOpenId(String openId) throws Exception {
        return sysUserService.findByOpenId(openId);
    }

    @GetMapping("/users/{id}")
    public SysUser findUserById(@PathVariable Integer id) throws Exception {
        return sysUserService.getById(id);
    }

    @PutMapping("/users")
    public void updateSysUser(@RequestBody SysUser sysUser) throws Exception {
        sysUserService.updateById(sysUser);
    }

    @PostMapping("/users/{id}/roles")
    public void setRoleToUser(@PathVariable Integer id, @RequestBody List<Integer> roleIds) throws Exception {
        sysUserService.setRoleToUser(id, roleIds);
    }

    @GetMapping("/users/{id}/roles")
    public List<SysRole> findRolesByUserId(@PathVariable Integer id) throws Exception {
        return sysUserService.findRolesByUserId(id);
    }

    @GetMapping("/users")
    public PageResult<SysUser> findUsers(@RequestParam Map<String, Object> params) throws Exception {
        return sysUserService.findUsers(params);
    }

    @GetMapping("/users/updateEnabled")
    public Result updateEnabled(@RequestParam Map<String, Object> params) throws Exception {
        Long id = MapUtils.getLong(params, "id");
        if (checkAdmin(id)) {
            return Result.failed(ADMIN_CHANGE_MSG);
        }
        return sysUserService.updateEnabled(params);
    }

    @PutMapping(value = "/users/{id}/password")
    public Result resetPassword(@PathVariable Integer id) throws Exception {
        if (checkAdmin(id)) {
            return Result.failed(ADMIN_CHANGE_MSG);
        }
        sysUserService.updatePassword(id, null, null);
        return Result.succeed("重置成功");
    }

    @PutMapping(value = "/users/password")
    public Result resetPassword(@RequestBody SysUser sysUser) throws Exception {
        if (checkAdmin(sysUser.getId())) {
            return Result.failed(ADMIN_CHANGE_MSG);
        }
        sysUserService.updatePassword(sysUser.getId(), sysUser.getOldPassword(), sysUser.getNewPassword());
        return Result.succeed("重置成功");
    }

    @DeleteMapping(value = "/users/{id}")
    public Result delete(@PathVariable Integer id) throws Exception {
        if (checkAdmin(id)) {
            return Result.failed(ADMIN_CHANGE_MSG);
        }
        sysUserService.delUser(id);
        return Result.succeed("删除成功");
    }

    @PostMapping("/users/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody SysUser sysUser) throws Exception {
        if (sysUser.getId() == null) {
            return sysUserService.add(sysUser);
        }
        return sysUserService.update(sysUser);
    }

    /**
     * 是否超级管理员
     */
    private boolean checkAdmin(long id) {
        return id == 1L;
    }
}
